<?php

namespace app\shop\controller;


use app\shop\model\user\User;
use wanyue\services\CacheService;
use wanyue\services\UtilService;
use think\facade\Session;
use think\facade\Route as Url;
use app\models\user\WechatUser;

/**
 * 登录验证控制器
 * Class Login
 * @package app\admin\controller
 */
class Login extends ShopBasic
{
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 登录验证 + 验证码验证
     */
    public function verify()
    {
        if (!request()->isPost()) return $this->failed('请登陆!');
        list($account, $captcha) = UtilService::postMore([
            'account', 'captcha'
        ], null, true);

        $key='shop_login_error';
        $error = Session::get($key) ?: ['num' => 0, 'time' => time()];
        $error['num'] = 0;
        if ($error['num'] >= 5 && $error['time'] > strtotime('- 5 minutes'))
            return $this->failed('错误次数过多,请稍候再试!');

        //验证验证码
        $verifyCode = CacheService::get('code_' . $account);
        if (!$verifyCode)
            return app('json')->fail('请先获取验证码');
        $verifyCode = substr($verifyCode, 0, 6);
        if ($verifyCode != $captcha)
            return app('json')->fail('验证码错误');


        //检验帐号密码
        $res = User::login($account);
        if ($res) {
            Session::set($key, null);
            Session::save();
            return $this->successful(['url' => Url::buildUrl('index/index')->build()]);
        } else {
            $error['num'] += 1;
            $error['time'] = time();
            Session::set($key, $error);
            Session::save();
            return $this->failed(User::getErrorInfo('账号信息，请重新输入'));
        }
    }

    /**
     * 退出登陆
     */
    public function logout()
    {
        User::clearLoginInfo();
        $this->redirect(Url::buildUrl('index')->build());
    }
}